package me.seu.demo.controller;

import lombok.extern.slf4j.Slf4j;
import me.seu.demo.entity.Item;
import me.seu.demo.repository.ItemRepository;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 从ES中查询数据
 *
 * @author liangfeihu
 * @since 2020/4/23 14:44
 */
@Slf4j
@RestController
@RequestMapping("/es/query")
public class EsQueryController {

    @Autowired
    ItemRepository itemRepository;

    @GetMapping("/match")
    public ResponseEntity matchQuery() {
        // 构建查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 添加基本分词查询
        queryBuilder.withQuery(QueryBuilders.matchQuery("title", "小米手机"));
        // 搜索，获取结果
        Page<Item> items = this.itemRepository.search(queryBuilder.build());
        // 总条数
        long total = items.getTotalElements();
        log.info("matchQuery total = {}", total);
        for (Item item : items) {
            log.info("Page<Item> items: {}", item);
        }

        return ResponseEntity.ok("match query data success");
    }

    @GetMapping("/bool")
    public ResponseEntity boolQuery() {
        // 构建查询条件
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.withQuery(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("title", "手机"))
                .must(QueryBuilders.termQuery("brand", "小米"))
        );
        // 搜索，获取结果
        Page<Item> list = this.itemRepository.search(builder.build());
        for (Item item : list) {
            log.info("Page<Item> list: {}", item);
        }

        return ResponseEntity.ok("bool query data success");
    }

    @GetMapping("/sort")
    public ResponseEntity searchAndSort() {
        // 构建查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 添加基本分词查询
        queryBuilder.withQuery(QueryBuilders.termQuery("category", "手机"));

        // 排序
        queryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.ASC));

        // 搜索，获取结果
        Page<Item> items = this.itemRepository.search(queryBuilder.build());
        // 总条数
        long total = items.getTotalElements();
        log.info("searchAndSort 总条数 = {}", total);

        for (Item item : items) {
            log.info("Page<Item> items: {}", item);
        }

        return ResponseEntity.ok("searchAndSort data success");
    }

}
